package co.edu.eam.iso.view;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import org.jfree.ui.ExtensionFileFilter;

import co.edu.eam.iso.enums.CharacteristicEnum;
import co.edu.eam.iso.enums.IconEnum;
import co.edu.eam.iso.logger.Logger;
import co.edu.eam.iso.model.Characteristic;
import co.edu.eam.iso.model.Evaluation;
import co.edu.eam.iso.model.dao.EvaluationDAO;
import co.edu.eam.iso.xml.XMLReader;

public class ManageEvaluationsDialog extends JDialog {

	private static final long serialVersionUID = 1L;
	
	private EvaluationDAO evaluationDAO;
	
	private JPanel contentPane;
	
	private JTable tblEvaluations;
	
	private Component parent;
	
	private DefaultTableModel defaultTableModel;
	
	private JButton btnDelete;
	private JButton btnView;
	private JButton btnUpload;

	private boolean enabledbuttons;

	public ManageEvaluationsDialog(Component parent) {
		this.parent = parent;
		this.evaluationDAO = EvaluationDAO.getInstance();
		initialize();
	}
	
	private void initialize() {
		setTitle("ISO 9126-1 - Gestionar evaluaciones");
		setBounds(100, 100, 498, 345);
		setModalityType(ModalityType.APPLICATION_MODAL);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setResizable(false);
		setLocationRelativeTo(parent);
		
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(null);		
		contentPane.add(createPanelEvaluations());
		setContentPane(contentPane);
		
		JButton btnCancel = new JButton("Cancelar");
		btnCancel.setBounds(385, 275, 90, 25);
		contentPane.add(btnCancel);
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				closeWindow();
			}
		});
	}
	
	private JPanel createPanelEvaluations() {
		JPanel panelEvaluations = new JPanel();
		panelEvaluations.setBorder(new TitledBorder(null, "Evaluaciones",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panelEvaluations.setBounds(5, 5, 483, 264);
		panelEvaluations.setLayout(null);

		JScrollPane scrollPaneEvaluations = new JScrollPane();		
		scrollPaneEvaluations.setBounds(51, 25, 419, 225);
		panelEvaluations.add(scrollPaneEvaluations);	
		
		tblEvaluations = new JTable();
		tblEvaluations.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tblEvaluations.setRowHeight(20);
		refreshTable();
		scrollPaneEvaluations.setViewportView(tblEvaluations);
		tblEvaluations.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (!enabledbuttons) {
					enableActionButtons(true);
				}
			}
		});
		
		btnUpload = new JButton();
		btnUpload.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					uploadEvaluation();
				} catch (Exception ex) {
					Logger.getInstance().registrarLog(ex);
					JOptionPane.showMessageDialog(ManageEvaluationsDialog.this,
							"Se ha presentado un error al cargar la evaluación.");
				}
			}
		});
		btnUpload.setToolTipText("Cargar");
		btnUpload.setIcon(getIcon(IconEnum.UPLOAD));
		btnUpload.setBounds(15, 25, 35, 35);
		panelEvaluations.add(btnUpload);
		
		btnView = new JButton();
		btnView.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				viewEvaluation();
			}
		});
		btnView.setEnabled(false);
		btnView.setToolTipText("Ver");
		btnView.setIcon(getIcon(IconEnum.VIEW));
		btnView.setBounds(15, 61, 35, 35);
		panelEvaluations.add(btnView);
		
		btnDelete = new JButton();
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				deleteEvaluation();
			}
		});
		btnDelete.setEnabled(false);
		btnDelete.setToolTipText("Eliminar");
		btnDelete.setIcon(getIcon(IconEnum.DELETE));
		btnDelete.setBounds(15, 97, 35, 35);
		panelEvaluations.add(btnDelete);
		
		return panelEvaluations;
	}
	
	private void closeWindow() {
		dispose();
	}
	
	private ImageIcon getIcon(IconEnum icon) {
		return new ImageIcon(getClass().getResource(icon.getLocation()));
	}	
	
	private void clearTable() {
		defaultTableModel = new DefaultTableModel(null, 
				new String[] { "Código", "Nombre", "Fecha"});	
		tblEvaluations.setModel(defaultTableModel);
		tblEvaluations.getColumnModel().getColumn(0).setPreferredWidth(60);
		tblEvaluations.getColumnModel().getColumn(1).setPreferredWidth(240);
		tblEvaluations.getColumnModel().getColumn(2).setPreferredWidth(135);
	}	
	
	private void refreshTable() {
		clearTable();
		List<Evaluation> evaluations = evaluationDAO.searchEvaluations();

		for (Evaluation evaluation : evaluations) {
			Object[] data = new Object[3];
			data[0] = evaluation.getId();
			data[1] = evaluation.getName();
			data[2] = evaluation.getDate();
			defaultTableModel.addRow(data);
		}
	}	
	
	private void enableActionButtons(boolean enable) {
		btnView.setEnabled(enable);
		btnDelete.setEnabled(enable);
		enabledbuttons = enable;
	}
	
	private void deleteEvaluation() {
		int row = tblEvaluations.getSelectedRow();
		int id = Integer.parseInt(tblEvaluations.getValueAt(row, 0).toString());
		int option = JOptionPane.showConfirmDialog(this, "¿Está seguro de eliminar la evaluación?",
				"Mensaje de advertencia", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
		
		if (option == JOptionPane.YES_OPTION) {
			evaluationDAO.deleteEvaluation(id);
			enableActionButtons(false);
			refreshTable();
		}
	}
	
	private void viewEvaluation() {
		int row = tblEvaluations.getSelectedRow();
		int id = Integer.parseInt(tblEvaluations.getValueAt(row, 0).toString());
		String name = tblEvaluations.getValueAt(row, 1).toString();
		
		try {
			Map<CharacteristicEnum, Characteristic> characteristics = evaluationDAO
					.searchEvaluationDetail(id);
			
			EvaluateChrtcsDialog evaluateChrtcs = new EvaluateChrtcsDialog(this, id, name, characteristics);
			evaluateChrtcs.setVisible(true);
			
			if (!name.equals(evaluateChrtcs.getEvaluationName())) {
				refreshTable();
			}
		} catch (Exception e) {
			Logger.getInstance().registrarLog(e);
			JOptionPane.showMessageDialog(this, e.getMessage());
		}
	}
	
	private void uploadEvaluation() throws Exception {
		String evaluationName = JOptionPane.showInputDialog(this,
				"Nombre de la evaluación");
		
		if (evaluationName != null && !evaluationName.isEmpty()) {
			File file = chooseFile();
			
			if (file != null) {
				XMLReader xmlReader = XMLReader.getInstance();
				Map<CharacteristicEnum, Characteristic> characteristics = xmlReader
						.readXML(file.getAbsolutePath());
				
				int evaluationId = EvaluationDAO.getInstance().saveEvaluation(
						0, evaluationName, characteristics);
				
				refreshTable();
				
				JOptionPane.showMessageDialog(ManageEvaluationsDialog.this,
						"Se ha cargado la evaluación " + evaluationId + " correctamente.");					
			}
		} else if (evaluationName != null && evaluationName.isEmpty()) {
			JOptionPane.showMessageDialog(this,
					"Debe ingresar el nombre de la evaluación.");
			uploadEvaluation();
		}
	}
	
	private File chooseFile() {
		ExtensionFileFilter xlsFilter = new ExtensionFileFilter("Archivo XML", "xml");  
		
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.addChoosableFileFilter( xlsFilter); 
		fileChooser.showOpenDialog(this);
		
		return fileChooser.getSelectedFile();
	}
	
}
